import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { Router } from '@angular/router';
import * as moment from 'moment';
import { ToastController } from '@ionic/angular';
import { Storage } from '@ionic/storage';
import { AppConsts } from '../../../shared/AppConsts';
import { SessionServiceProxy, WorkOrderServiceProxy, WorkScadaRepairProcessingRecordInput } from '../../../shared/service-proxies/service-proxies';

@Component({
  selector: 'app-scada-detail',
  templateUrl: './scada-detail.page.html',
  styleUrls: ['./scada-detail.page.scss'],
})
export class ScadaDetailPage implements OnInit {

  page: WorkScadaRepairProcessingRecordInput = new WorkScadaRepairProcessingRecordInput();

  userInfo: any;
  scadaData: any;
  reply: any;
  loginId: any;

  constructor(
    public routeData: ActivatedRoute,
    public router: Router,
    private storage: Storage,
    public toastCtrl: ToastController,
    private _SessionServiceProxy: SessionServiceProxy,
    public _WorkOrderServiceProxy: WorkOrderServiceProxy
  ) {
    this.routeData.params.subscribe((data) => {
      this.scadaData = data;
      console.log(this.scadaData);
    })
  }
  ionViewDidEnter(){
    this.checkLogin();
  }
  async checkLogin(){
    let h = await this.storage.get('accessToken');
   //  console.log(".............", h);
    if(!!h){
      AppConsts.sessonToken = h;
    } else {
      this.router.navigate(['login'])
    }
    this.getUserInfo();
 }
  ngOnInit() {
    this.getUserInfo();
  }

  async toastTip(message: string) {
    let toast = await this.toastCtrl.create({
      message: message,
      duration: 1500,
      position: 'middle'
    });
    toast.present();
  }

  goBack() {
    this.router.navigateByUrl('home')
  }

  getUserInfo() {
    this._SessionServiceProxy.getCurrentLoginInformations()
      .subscribe((res) => {
        this.userInfo = res;
        if (this.userInfo.user == undefined) {
          console.log(222)
        } else {
          this.loginId = this.userInfo.user.id;
        }

      })
  }

  submit() {
    if (this.loginId == this.scadaData.handler) {
      this.page.userId = this.scadaData.handler;
      this.page.userName = this.scadaData.handlerName;
      this.page.departmentId = this.scadaData.handlerOrgId;
      this.page.departmentName = this.scadaData.handlerOrgName;
      this.page.description = this.reply;
      this.page.repairId = this.scadaData.id;
      this.page.result = 0;
      this._WorkOrderServiceProxy.editScadaRepairProcessingOrder(this.page)
        .subscribe((res) => {
          console.log(res);
          this.toastTip('处理成功');
          setTimeout( this.router.navigateByUrl('scada'), 1500 )
         ;
        })
    } else {
      this.toastTip('你无权处理');
    }

  }

}
